import React, { useEffect,useRef } from 'react'
import { Modal, Form, Input, message } from 'antd';
import { useRequest } from 'ahooks'
import _ from 'lodash';
import axios from 'axios';

// 发起网络请求，添加新闻类型
const addCategoryListRequest = (item: any, type: string) => {
    console.log(item);
    switch (type) {
        case 'add':
            return axios.post(`http://localhost:3000/categories`, {
                ...item
            })
        case 'modify':
            return axios.patch(`http://localhost:3000/categories/${item.id}`, {
                ...item
            })
        default:
            return axios.patch(`http://localhost:3000/categories`, {
                ...item
            })
    }

};

type stringKey = Record<string, string>;
export default function CategoryModal(props: any) {
    const modelTitleObj: stringKey = {
        'add': '新增',
        'modify': '修改'
    }
    //对表单数据域进行交互
    const [form] = Form.useForm();
    const { addOpen, setAddOpen, getCategoryListData, modelType, currentItem } = props;
    console.log(props);
    // useRequest - 获取所有新闻类型
    const { run: addCategoryListData, loading: addCategoryLoading } = useRequest(addCategoryListRequest, {
        throttleWait: 300,
        manual: true,
        onSuccess: (result: any, params) => {
            console.log(result.status);
            if (result.status < 300) {
                switch (params[1]) {
                    case 'add':
                        getCategoryListData();
                        setAddOpen(false);
                        form.resetFields();
                        message.success('新增新闻分类数据成功')
                        break;
                    case 'modify':
                        console.log('modify');
                        getCategoryListData();
                        setAddOpen(false);
                        form.resetFields();
                        message.success('修改新闻分类数据成功')
                        break;
                    default:
                        break;
                }
            }
        },
        onError(e, params) {
            message.warning('新增新闻分类数据失败')
        },
    });
    // 添加对话框的确定按钮，点击回调事件
    const handelOperation = () => {
        switch (modelType) {
            case 'add':
                console.log('添加新闻');
                form.validateFields()
                    .then((values) => {
                        const completeItem = _.cloneDeep(values);
                        completeItem.title = values.value;
                        addCategoryListData(completeItem, 'add');
                    })
                    .catch((info) => {
                        console.log('错误信息:', info);
                    });
                break;
            case 'modify':
                console.log('修改新闻');
                form.validateFields()
                    .then((values) => {
                        console.log(values);
                        const completeItem = _.cloneDeep(values);
                        completeItem.title = values.value;
                        completeItem.id = currentItem.id;
                        addCategoryListData(completeItem, 'modify');
                    })
                    .catch((info) => {
                        console.log('错误信息:', info);
                    });
                break;
            default:
                break;
        }

    };
    //监听Form是否渲染
    const formRef=useRef(null);
    useEffect(() => {
        if(formRef.current){
            currentItem && form.setFieldsValue(currentItem);
        }
        
    }, [currentItem])
    return (
        <div>
            <Modal
                title={`${modelTitleObj[modelType]}`}
                open={addOpen}
                onOk={() => { handelOperation() }}
                confirmLoading={addCategoryLoading}
                onCancel={() => { setAddOpen(false); }}
                okText='确定'
                cancelText='取消'
            >
                <Form
                    name="basic"
                    initialValues={{ remember: true }}
                    autoComplete="off"
                    form={form}
                    ref={formRef}
                >
                    <Form.Item
                        label="新闻分类"
                        name="value"
                        rules={[{ required: true, message: '请输入新闻分类!' }]}
                    >
                        <Input />
                    </Form.Item>
                </Form>
            </Modal>
        </div>
    )
}
